/*
 * Copyright 2024 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.pajamas.starter.integration.spring.jdbc;

import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.pajmas.daydream.building.AbstractEzBuilder;
import org.springframework.boot.autoconfigure.liquibase.LiquibaseProperties;

import javax.sql.DataSource;

import liquibase.integration.spring.SpringLiquibase;

/**
 * @author william
 * @since 2024/1/18
 */

public final class LiquibaseBuilder extends AbstractEzBuilder<SpringLiquibase> {
    private DataSource dataSource;
    private String changelog;
    private Boolean dropFirst;
    private Boolean shouldRun;
    private final LiquibaseProperties properties;

    private LiquibaseBuilder(LiquibaseProperties properties) {
        this.properties = properties;
    }

    public static LiquibaseBuilder newBuilder(LiquibaseProperties properties) {
        return new LiquibaseBuilder(properties);
    }

    public LiquibaseBuilder dataSource(DataSource dataSource) {
        this.dataSource = dataSource;
        return this;
    }

    public LiquibaseBuilder changelog(String changelog) {
        this.changelog = changelog;
        return this;
    }

    public LiquibaseBuilder dropFirst(Boolean dropFirst) {
        this.dropFirst = dropFirst;
        return this;
    }

    public LiquibaseBuilder shouldRun(Boolean shouldRun) {
        this.shouldRun = shouldRun;
        return this;
    }

    @Override
    public SpringLiquibase internalBuild() {
        SpringLiquibase springLiquibase = new SpringLiquibase();
        springLiquibase.setDataSource(this.dataSource);
        springLiquibase.setChangeLog(StringUtils.firstNonBlank(this.changelog, this.properties.getChangeLog()));
        springLiquibase.setShouldRun(ObjectUtils.firstNonNull(this.shouldRun, this.properties.isEnabled()));
        springLiquibase.setDropFirst(ObjectUtils.firstNonNull(this.dropFirst, this.properties.isDropFirst()));
        return springLiquibase;
    }

    public interface Customizer extends AbstractEzBuilder.Customizer<SpringLiquibase, LiquibaseBuilder> {
    }
}
